#include "../DWMRICore/Fiber.h"
#include "../DWMRICore/Scalar.h"
#include "../DWMRICore/DTI.h"

#include "LeastSquare.h"

#include <teem\ell.h>

#include <omp.h>

char *fiber_pathname = NULL;
char *dst_pathname = NULL;

char **confPathname = NULL;
char **vertPathname = NULL;
int w, h, d, scale;
float stepSize, maxLength;

int kernel_size = 0;
float fiber_length = 0.0f;

#ifndef PARAM_COUNT
#define PARAM_COUNT 17
#endif

#ifndef RESAMPLE
#define RESAMPLE 10
#endif

float weights[PARAM_COUNT];

struct FiberParameter {
	Seed seed;
	CPoint3F parameters[PARAM_COUNT];
};

void PrintUsage()
{
	printf("Usage: ComputeMyEdgeStrength -fiber <configure_file> -dst <dst_file> -length <fiber_length> -kernel <kernel_size>\n");
}

int ParseArguments(const int argc, char *argv[])
{
	for (int i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "-fiber") == 0) {
			fiber_pathname = argv[++i];
		} else if (strcmp(argv[i], "-dst") == 0) {
			dst_pathname = argv[++i];
		} else if (strcmp(argv[i], "-length") == 0) {
			fiber_length = (float)atof(argv[++i]);
		} else if (strcmp(argv[i], "-kernel") == 0) {
			kernel_size = atoi(argv[++i]);
		} else {
			return -1;
		}
	}

	if (fiber_pathname == NULL || dst_pathname == NULL || fiber_length < 0.0001f || kernel_size == 0)
		return -2;

	return 0;
}

void FiberParameterization(CFiber *fibers, FiberParameter *parameters, const int count)
{
	int offset = int(fiber_length / stepSize * (float)RESAMPLE / (float)((PARAM_COUNT-1)/2));
	for (int i = 0; i < count; ++i) {
		parameters[i].seed = fibers[i].m_seed;
		parameters[i].parameters[PARAM_COUNT/2] = fibers[i].m_seed.pos;

		// forward
		
		if (fibers[i].m_fCount < 2) {
			for (int j = 0; j < (PARAM_COUNT-1)/2; ++j) {
				parameters[i].parameters[PARAM_COUNT/2+j+1] = fibers[i].m_seed.pos;
			}
		} else {
			int resamples_size = (fibers[i].m_fCount - 1) * RESAMPLE;
			CPoint3F *resamples = new CPoint3F[resamples_size];

			for (uint j = 1; j < fibers[i].m_fCount; ++j) {
				for (int k = 0; k < RESAMPLE; ++k) {
					float ratio = float(k+1) / float(RESAMPLE);
					resamples[(j-1)*RESAMPLE+k] = fibers[i].m_pF[j-1] * (1.0f - ratio) + fibers[i].m_pF[j] * ratio;
				}
			}
			for (int j = 0; j < (PARAM_COUNT-1)/2; ++j) {
				int id = (j + 1) * offset;
				id = id < resamples_size ? id : (resamples_size-1);
				parameters[i].parameters[PARAM_COUNT/2+j+1] = resamples[id];
			}
			SafeDeleteArray(resamples);
		}
		

		// backward
		if (fibers[i].m_bCount < 2) {
			for (int j = 0; j < (PARAM_COUNT-1)/2; ++j) {
				parameters[i].parameters[PARAM_COUNT/2-j-1] = fibers[i].m_seed.pos;
			}
		} else {
			int resamples_size = (fibers[i].m_bCount - 1) * RESAMPLE;
			CPoint3F *resamples = new CPoint3F[resamples_size];
			for (uint j = 1; j < fibers[i].m_bCount; ++j) {
				for (int k = 0; k < RESAMPLE; ++k) {
					float ratio = float(k+1) / float(RESAMPLE);
					resamples[(j-1)*RESAMPLE+k] = fibers[i].m_pB[j-1] * ratio + fibers[i].m_pB[j] * (1.0f - ratio);
				}
			}
			for (int j = 0; j < (PARAM_COUNT-1)/2; ++j) {
				int id = (j + 1) * offset;
				id = id < resamples_size ? id : (resamples_size-1);
				parameters[i].parameters[PARAM_COUNT/2-j-1] = resamples[id];
			}
			SafeDeleteArray(resamples);
		}
		
	}
}

void ComputeTensor(FiberParameter *fibers, const int count, float *tensor, const int id)
{
	/* construct matrix A */
	double *A = new double[count*4];
	for (int i = 0; i < count; ++i) { 
		A[i*4+0] = (fibers[i].seed.pos.m_x - fibers[0].seed.pos.m_x) * (double)scale;
		A[i*4+1] = (fibers[i].seed.pos.m_y - fibers[0].seed.pos.m_y) * (double)scale;
		A[i*4+2] = (fibers[i].seed.pos.m_z - fibers[0].seed.pos.m_z) * (double)scale;
		A[i*4+3] = 1.0;
	}

	/* compute pseudoinverse of matrix A */
	double *pinvA = new double[4*count];
	PseudoInverse4(A, pinvA, count, 4);

	/* estimate the function for each parameter */
	float *x = new float[4];
	float *y = new float[count];
	for (int j = 0; j < 3; ++j) {
		for (int k = 0; k < count; ++k) { 
			if (j == 0)
				y[k] = fibers[k].parameters[id].m_x;
			else if (j == 1)
				y[k] = fibers[k].parameters[id].m_y;
			else
				y[k] = fibers[k].parameters[id].m_z;
		}
		memset(x, 0, sizeof(float)*4);

		//LeastSquare(A, x, y, count, 3);
		LeastSquareFast4(pinvA, x, y, count, 4);

		tensor[1] += x[0] * x[0];
		tensor[2] += x[0] * x[1];
		tensor[3] += x[0] * x[2];
		tensor[4] += x[1] * x[1];
		tensor[5] += x[1] * x[2];
		tensor[6] += x[2] * x[2];
	}


	SafeDeleteArray(A);
	SafeDeleteArray(pinvA);
	SafeDeleteArray(x);
	SafeDeleteArray(y);
}


void ComputeTensor(FiberParameter *fibers, const int count, float *tensor)
{
	/* construct matrix A */
	double *A = new double[count*4];
	for (int i = 0; i < count; ++i) { 
		A[i*4+0] = (fibers[i].seed.pos.m_x - fibers[0].seed.pos.m_x) * (double)scale;
		A[i*4+1] = (fibers[i].seed.pos.m_y - fibers[0].seed.pos.m_y) * (double)scale;
		A[i*4+2] = (fibers[i].seed.pos.m_z - fibers[0].seed.pos.m_z) * (double)scale;
		A[i*4+3] = 1.0;
	}

	/* compute pseudoinverse of matrix A */
	double *pinvA = new double[4*count];
	PseudoInverse4(A, pinvA, count, 4);

	/* estimate the function for each parameter */
	float *x = new float[4];
	float *y = new float[count];
	for (int i = 0; i < PARAM_COUNT; ++i) {
		for (int j = 0; j < 3; ++j) {
			for (int k = 0; k < count; ++k) { 
				if (j == 0)
					y[k] = fibers[k].parameters[i].m_x;
				else if (j == 1)
					y[k] = fibers[k].parameters[i].m_y;
				else
					y[k] = fibers[k].parameters[i].m_z;
			}
			memset(x, 0, sizeof(float)*4);

			//LeastSquare(A, x, y, count, 3);
			LeastSquareFast4(pinvA, x, y, count, 4);

			tensor[1] += weights[i] * x[0] * x[0];
			tensor[2] += weights[i] * x[0] * x[1];
			tensor[3] += weights[i] * x[0] * x[2];
			tensor[4] += weights[i] * x[1] * x[1];
			tensor[5] += weights[i] * x[1] * x[2];
			tensor[6] += weights[i] * x[2] * x[2];
		}
	}

	SafeDeleteArray(A);
	SafeDeleteArray(pinvA);
	SafeDeleteArray(x);
	SafeDeleteArray(y);
}

void ReverseFiber(FiberParameter *fiber)
{
	fiber->seed.dir.m_x = -fiber->seed.dir.m_x;
	fiber->seed.dir.m_y = -fiber->seed.dir.m_y;
	fiber->seed.dir.m_z = -fiber->seed.dir.m_z;

	for (int i = 0; i < PARAM_COUNT/2; ++i) {
		//swap i with PARAM_COUNT-i-1
		CPoint3F temp = fiber->parameters[i];
		fiber->parameters[i] = fiber->parameters[PARAM_COUNT-i-1];
		fiber->parameters[PARAM_COUNT-i-1] = temp;
	}
}

void ComputeWeights()
{
	float *st = new float[w*h*7];
	
	CFiber *fibers = NULL;
	FiberParameter **parameters = new FiberParameter*[2*(kernel_size+1)+1];
	for (int i = 0; i < 2*(kernel_size+1)+1; ++i) {
		parameters[i] = new FiberParameter[w*h];
	}

	int offset[9];
	offset[ 0] = 0;		offset[ 1] = -1;	offset[ 2] = 1;
	offset[ 3] = -w-1;	offset[ 4] = -w;	offset[ 5] = -w+1;
	offset[ 6] = w-1;	offset[ 7] = w;		offset[ 8] = w+1;

	int ks = 2 * kernel_size + 1;
	float *gaussian = new float[ks*ks*ks];
	for (int z = 0; z < ks; ++z) {
		for (int y = 0; y < ks; ++y) {
			for (int x = 0; x < ks; ++x) {
				int index = (z * ks + y) * ks + x;
				float dis = float((x - kernel_size) * (x - kernel_size) + (y - kernel_size) * (y - kernel_size) + (z - kernel_size) * (z - kernel_size));
				gaussian[index] = exp(-dis / (0.25f * ks * ks));
			}
		}
	}

	for (int z = d/2-kernel_size-1; z <= d/2+kernel_size+1; ++z) {
		int cw, ch;
		ReadFibers(confPathname[z], vertPathname[z], &fibers, cw, ch);
		FiberParameterization(fibers, parameters[z-(d/2-kernel_size-1)], cw*ch);
		delete[] fibers;
	}

	omp_set_num_threads(64);

	for (int k = 0; k < PARAM_COUNT; ++k) {
		memset(st, 0, sizeof(float)*w*h*7);

		for (int y = kernel_size + 1; y < h - kernel_size - 1; ++y) {
#pragma omp parallel for            
			for (int x = kernel_size + 1; x < w - kernel_size - 1; ++x) {
				int index = y * w + x;
				CVector3F base_dir = parameters[kernel_size+1][index].seed.dir;

				for (int cz = -kernel_size; cz <= kernel_size; ++cz) {
					for (int cy = -kernel_size; cy <= kernel_size; ++cy) { 
						for (int cx = -kernel_size; cx <= kernel_size; ++cx) {
							int temp_index = (y + cy) * w + (x + cx);

							FiberParameter f[27];

							for (int i = 0; i < 9; ++i) {
								memcpy(&(f[i]), &(parameters[1+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i]));
								}
								memcpy(&(f[i+9]), &(parameters[0+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i+9].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i+9]));
								}
								memcpy(&(f[i+18]), &(parameters[2+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i+18].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i+18]));
								}
							}

							float temp_tensor[7] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
							ComputeTensor(f, 27, temp_tensor, k);

							int kx = kernel_size + cx;
							int ky = kernel_size + cy;
							int kz = kernel_size + cz;
							int gk_index = (kz * ks + ky) * ks + kx;

							st[(index)*7+0] += gaussian[gk_index] * temp_tensor[0];
							st[(index)*7+1] += gaussian[gk_index] * temp_tensor[1];
							st[(index)*7+2] += gaussian[gk_index] * temp_tensor[2];
							st[(index)*7+3] += gaussian[gk_index] * temp_tensor[3];
							st[(index)*7+4] += gaussian[gk_index] * temp_tensor[4];
							st[(index)*7+5] += gaussian[gk_index] * temp_tensor[5];
							st[(index)*7+6] += gaussian[gk_index] * temp_tensor[6];
						}
					}
				}
			}
		}

		weights[k] = 0.0f;

		/* compute weights */
		CDTI *pST = new CDTI();
		pST->CreateDTI(w, h, 1);
		for (int z = 0; z < 1; ++z) {
			for (int y = 0; y < h; ++y) {
				for (int x = 0; x < w; ++x) {
					int index = (z * h + y) * w + x;
					pST->SetDTI(x, y, z, &(st[index*7]));
					float dti[7];
					pST->GetDTIFast(x, y, z, dti);
					float eval[3], evec[9];
					pST->DTI2Eigen(dti, eval, evec);
					if (eval[0] > weights[k])
						weights[k] = eval[0];
				}
			}
		}

		weights[k] = 1.0f / weights[k];
		printf("weight %d is %f\n", k, weights[k]);

		SafeDelete(pST);
	}


	SafeDeleteArray(st);
	SafeDeleteArray(gaussian);

	for (int i = 0; i < 2*(kernel_size+1)+1; ++i) {
		SafeDeleteArray(parameters[i]);
	}
	SafeDeleteArray(parameters);
}

int main(int argc, char *argv[])
{
	if (ParseArguments(argc, argv) != 0) {
		PrintUsage();
		return 0;
	}

	/* read the configure file */
	ReadConfigureFile(fiber_pathname, &confPathname, &vertPathname, w, h, d, scale, stepSize, maxLength);

	float length = fiber_length > maxLength ? maxLength : fiber_length;
	int cw, ch;

	// compute weight for each parameter
	ComputeWeights();

	/* compute the structure tensor for each voxel */
	float *st = new float[w*h*d*7];
	memset(st, 0, sizeof(float)*w*h*d);

	CFiber *fibers = NULL;
	FiberParameter **parameters = new FiberParameter*[2*(kernel_size+1)+1];
	for (int i = 0; i < 2*(kernel_size+1)+1; ++i) {
		parameters[i] = new FiberParameter[w*h];
	}

	for (int z = 0; z < 2*(kernel_size+1); ++z) {
		ReadFibers(confPathname[z], vertPathname[z], &fibers, cw, ch);
		FiberParameterization(fibers, parameters[z], cw*ch);
		delete[] fibers;
	}
	
	int offset[9];
    offset[ 0] = 0;		offset[ 1] = -1;	offset[ 2] = 1;
    offset[ 3] = -w-1;	offset[ 4] = -w;	offset[ 5] = -w+1;
    offset[ 6] = w-1;	offset[ 7] = w;		offset[ 8] = w+1;

	int ks = 2 * kernel_size + 1;
	float *gaussian = new float[ks*ks*ks];
	for (int z = 0; z < ks; ++z) {
		for (int y = 0; y < ks; ++y) {
			for (int x = 0; x < ks; ++x) {
				int index = (z * ks + y) * ks + x;
				float dis = float((x - kernel_size) * (x - kernel_size) + (y - kernel_size) * (y - kernel_size) + (z - kernel_size) * (z - kernel_size));
				gaussian[index] = exp(-dis / (0.25f * ks * ks));
			}
		}
	}

	omp_set_num_threads(64);

	for (int z = kernel_size + 1; z < d - kernel_size - 1; ++z) {
		ReadFibers(confPathname[z+kernel_size+1], vertPathname[z+kernel_size+1], &fibers, cw, ch);
		FiberParameterization(fibers, parameters[2*(kernel_size+1)], cw*ch);
		delete[] fibers;

		for (int y = kernel_size + 1; y < h - kernel_size - 1; ++y) {
#pragma omp parallel for            
			for (int x = kernel_size + 1; x < w - kernel_size - 1; ++x) {
				int index = y * w + x;
				CVector3F base_dir = parameters[kernel_size+1][index].seed.dir;

				for (int cz = -kernel_size; cz <= kernel_size; ++cz) {
					for (int cy = -kernel_size; cy <= kernel_size; ++cy) { 
						for (int cx = -kernel_size; cx <= kernel_size; ++cx) {
							int temp_index = (y + cy) * w + (x + cx);

							FiberParameter f[27];

							for (int i = 0; i < 9; ++i) {
								memcpy(&(f[i]), &(parameters[1+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i]));
								}
								memcpy(&(f[i+9]), &(parameters[0+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i+9].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i+9]));
								}
								memcpy(&(f[i+18]), &(parameters[2+cz+kernel_size][temp_index+offset[i]]), sizeof(FiberParameter));
								if (InnerProduct(base_dir, f[i+18].seed.dir) < 0.0f) {
									ReverseFiber(&(f[i+18]));
								}
							}

							float temp_tensor[7] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
							ComputeTensor(f, 27, temp_tensor);

							int kx = kernel_size + cx;
							int ky = kernel_size + cy;
							int kz = kernel_size + cz;
							int gk_index = (kz * ks + ky) * ks + kx;

							st[(z*w*h+index)*7+0] += gaussian[gk_index] * temp_tensor[0];
							st[(z*w*h+index)*7+1] += gaussian[gk_index] * temp_tensor[1];
							st[(z*w*h+index)*7+2] += gaussian[gk_index] * temp_tensor[2];
							st[(z*w*h+index)*7+3] += gaussian[gk_index] * temp_tensor[3];
							st[(z*w*h+index)*7+4] += gaussian[gk_index] * temp_tensor[4];
							st[(z*w*h+index)*7+5] += gaussian[gk_index] * temp_tensor[5];
							st[(z*w*h+index)*7+6] += gaussian[gk_index] * temp_tensor[6];
						}
					}
				}
			}
		}

		for (int i = 0; i < 2*(kernel_size+1); ++i) {
			memcpy(parameters[i], parameters[i+1], sizeof(FiberParameter)*w*h);
		}
		memset(parameters[2*(kernel_size+1)], 0, sizeof(FiberParameter)*w*h);

		printf("z = %d\n", z);
	}

	/* save the result */
	CDTI *pST = new CDTI();
	pST->CreateDTI(w, h, d);
	for (int z = 0; z < d; ++z) {
		for (int y = 0; y < h; ++y) {
			for (int x = 0; x < w; ++x) {
				int index = (z * h + y) * w + x;
				pST->SetDTI(x, y, z, &(st[index*7]));
			}
		}
	}
	pST->SaveDTIFile(dst_pathname);
	SafeDelete(pST);


	/* free memory */
	for (int z = 0; z < d; ++z) {
		SafeDeleteArray(confPathname[z]);
		SafeDeleteArray(vertPathname[z]);
	}
	SafeDeleteArray(confPathname);
	SafeDeleteArray(vertPathname);

	SafeDeleteArray(st);
	SafeDeleteArray(gaussian);

	for (int i = 0; i < 2*(kernel_size+1)+1; ++i) {
		SafeDeleteArray(parameters[i]);
	}
	SafeDeleteArray(parameters);

	return 0;
}